<template>
  <Navbar title="购物车"></Navbar>

  <van-card
    v-for="item in cartList"
    :key="item.cartid"
    :num="item.num"
    :price="(item.originprice * item.discount) / 10"
    :title="item.proname"
  >
    <template #thumb>
      <div style="display: flex">
        <van-checkbox
          v-model="item.checked"
          @change="(e) => itemCheck(e, item)"
        ></van-checkbox>
        <img :src="item.img1" style="width: 50px; height: 50px" alt="" />
      </div>
    </template>
  </van-card>

  <van-submit-bar
    :price="price"
    button-text="提交订单"
    @submit="onSubmit"
    :placeholder="true"
  >
    <van-checkbox v-model="checked" @click="allCheck"
      >全选 {{ checked }}</van-checkbox
    >
  </van-submit-bar>
</template>

<script setup lang="ts">
import Navbar from "@/components/Navbar.vue";
import { cartApi } from "@/api/detail";
import { onMounted, ref, computed } from "vue";
import { watch } from "vue";

const cartList = ref<any[]>([]);
const getCartList = async () => {
  const res: any = await cartApi({
    userid: localStorage.getItem("userid") || "",
  });
  if (res) {
    cartList.value = res.data.map((item: any) => ({ ...item, checked: false }));
  }
};
onMounted(() => {
  getCartList();
});

const onSubmit = () => {
  alert("付款成功");
};
const checked = ref<boolean>(false);
// watch(checked, (val) => {
//   console.log(val);
//   cartList.value = cartList.value.map((item) => ({ ...item, checked: val }));
// });
// watch(
//   cartList,
//   (val) => {
//     const trueList = val.filter((item) => item.checked);
//     if (trueList.length === val.length) {
//       checked.value = true;
//     } else {
//       checked.value = false;
//     }
//   },
//   { deep: true }
// );

const allCheck = () => {
  cartList.value = cartList.value.map((item) => ({
    ...item,
    checked: checked.value,
  }));
};

const itemCheck = (e: boolean, item: any) => {
  const trueList = cartList.value.filter((item: any) => item.checked);
  if (trueList.length === cartList.value.length) {
    checked.value = true;
  } else {
    checked.value = false;
  }
};

// const price = ref<number>(0);
const price = computed(() => {
  return cartList.value
    .filter((item) => item.checked)
    .reduce((sum, item) => {
      return (sum +=
        ((item.originprice * item.discount * item.num) / 10) * 100);
    }, 0);
});
</script>

<style scoped lang="less">
:deep(.van-submit-bar) {
  bottom: 50px;
}
</style>
